package cn.com.push;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;

/**
 * ClassName: PushService
 * 
 * @Description: 推送工具类
 * @author yewl
 * @date 2017年4月28日
 */
public class PushService {
	protected static final Logger LOG = LogManager.getLogger(PushService.class.getName());

	/**
	 * @Description: 推送通知
	 * @param phones
	 *            要推送的用户手机号
	 * @param content
	 *            通知的内容
	 */
	public static void pushNotification(String[] phones, String content) throws Exception {
		JPushClient jpushClient = new JPushClient(Keyandsecretkey.masterSecret, Keyandsecretkey.appKey, 3);
		PushPayload build = PushPayload.newBuilder().setPlatform(Platform.all()).setAudience(Audience.alias(phones))
				.setNotification(Notification.alert(content)).build();
		// PushResult result = jpushClient.sendPush(build);
		// LOG.info("Got result - " + result);
		try {
			PushResult result = jpushClient.sendPush(build);
			LOG.info("Got result - " + result);
		} catch (APIConnectionException e) {
			// Connection error, should retry later
			LOG.error("Connection error, should retry later", e);
			throw e;
		} catch (APIRequestException e) {
			// Should review the error, and fix the request
			LOG.error("Should review the error, and fix the request", e);
			LOG.info("HTTP Status: " + e.getStatus());
			LOG.info("Error Code: " + e.getErrorCode());
			LOG.info("Error Message: " + e.getErrorMessage());
			throw e;
		}
	}

	public static void main(String[] args) {
		String[] mobiles = new String[] { "18616783665" };
		try {
			pushNotification(mobiles, "ceshidawdw");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
